<template>
  <UploadExcel :on-success="upload" />
</template>

<script>
import { importEmployee } from '@/api/employees'
export default {
  methods: {
    async upload(data) {
      const newResults = data.results.map(user => {
        return this.transformKey(user)
      })
      await importEmployee(newResults)
      this.$message.success('导入成功')
      this.$router.push('/employees')
      // this.$router.back()
    },
    // 转换key
    transformKey(user) {
      // 字典
      const dictionaries = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const newUser = {}
      for (const key in user) {
        const newKey = dictionaries[key]
        if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
          newUser[newKey] = new Date(this.formatDateExcel(user[key], '/'))
        } else {
          newUser[newKey] = user[key]
        }
      }
      return newUser
    },
    // 转换excel时间 传入时间和分隔符
    formatDateExcel(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
